package com.thm.tfast.core.exception;

import cn.hutool.http.HttpStatus;
import com.thm.tfast.core.entity.ViewResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author THM
 * @date 2022/5/14
 * @desc 全局异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public ViewResult<String> handleException(Exception e){
        e.printStackTrace();
        return ViewResult.error("系统错误",e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public ViewResult<String> handle(ApiException e) {
        return ViewResult.error(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ViewResult<String> handleValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return ViewResult.error(HttpStatus.HTTP_BAD_REQUEST,message);
    }

    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public ViewResult<String> handleValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = null;
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField()+fieldError.getDefaultMessage();
            }
        }
        return ViewResult.error(HttpStatus.HTTP_NOT_FOUND,message);
    }
}
